
#include "moduleloadlibrarywindows.h"
#include <windows.h>
#include <winbase.h>
#include <tchar.h>

CModuleLoadLibraryWindows::CModuleLoadLibraryWindows()
{
}

CModuleLoadLibraryWindows::~CModuleLoadLibraryWindows()
{
}

void* CModuleLoadLibraryWindows::Open(std::string path)
{
  return reinterpret_cast<void*>(::LoadLibrary(_T(path.c_str())));
}

int CModuleLoadLibraryWindows::Close(void *handle)
{
  return ::FreeLibrary(reinterpret_cast<HMODULE>(handle));
}
   
void* CModuleLoadLibraryWindows::Load(void *handle, std::string symbol)
{
  return static_cast<void*>(::GetProcAddress(reinterpret_cast<HMODULE>(handle),
                            symbol.c_str()));
}

std::string CModuleLoadLibraryWindows::getErrorDescription()
{
  std::string ret_string;

#if 0
  // Retrieve the system error message for the last-error code
  // The soyrce code form the MSDN (ms-help://MS.MSDNQTR.v90.en/debug/base/retrieving_the_last_error_code.htm)
  LPVOID lpMsgBuf;
  LPVOID lpDisplayBuf;
  DWORD dw = GetLastError(); 

  FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

  // Display the error message and exit the process

  lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 

    ret_string = lpDisplayBuf;
    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
#endif
    return ret_string;
}


